const express = require("express");
const { sqlFn } = require("../mysql");
const { sign } = require("jsonwebtoken");
const { jwtSecret } = require("../config");

const router = express.Router();

router.post("/", (req, res) => {
  const { username, password } = req.body;
  const sql = "select * from user where username=? and password=?";
  const arr = [username, password];
  sqlFn(sql, arr, (data) => {
    if (data.length) {
      const token = sign(
        {
          id: data[0].id,
          username: data[0].username,
        },
        jwtSecret
      );
      res.json({ token, success: true, errors: {} });
    } else {
      res.status(401).json({ errors: { form: "用户名或密码错误" } });
    }
  });
});

module.exports = router;
